﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace DusonFramework.Config.MyConfig
{
    public class ConfigHelper
    {
        private static IConfig _configMgr = ConfigFactory.CreateConfig();
        //private static ICache _cacheMgr = CacheFactory.CreateCache();

        /// <summary>
        /// 获得配置文件的配置项
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        private static T GetAppConfigValue<T>(string key, T defaultValue = default(T))
        {
            // 可以借助缓存提高性能
            //if (!_cacheMgr.Contains(key))
            //{
                string result = ConfigurationManager.AppSettings[key];
                if (string.IsNullOrWhiteSpace(result) && defaultValue != null)
                    result = defaultValue.ToString();
                if (string.IsNullOrWhiteSpace(result))
                    return default(T);

                T value = (T)Convert.ChangeType(result, typeof(T));
                if (value == null)
                    value = defaultValue;

                // 缓存依赖于配置文件
                string appSettingFilePath = AppDomain.CurrentDomain.BaseDirectory + "Config\\AppSettings.config";
            //    _cacheMgr.AddWithFilesDepend(key, value, appSettingFilePath);
            //}

            //return (T)_cacheMgr.Get(key);
                return value;
        }

        /// <summary>
        /// 获取配置值，不能获得则返回默认值
        /// </summary>
        /// <typeparam name="T">值类型</typeparam>
        /// <param name="key">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值</returns>
        private static T GetConfigValue<T>(string key, T defaultValue)
        {
            // 可以借助缓存提高性能
            //if (!_cacheMgr.Contains(key))
            //{
                string result = _configMgr.GetValueByKey(key);
                if (string.IsNullOrWhiteSpace(result) && defaultValue != null)
                    result = defaultValue.ToString();
                if (string.IsNullOrWhiteSpace(result))
                    return default(T);

                T value = (T)Convert.ChangeType(result, typeof(T));
                if (value == null)
                    value = defaultValue;

                //_cacheMgr.Add(key, value);
            //}

            //return (T)_cacheMgr.Get(key);

                return value;
        }

    }
}
